#!/usr/bin/env python3

import gt
import os
import random

"""
    全局变量的定义
"""
#   画布大小
ROW, COL = 15, 60
#   球的属性描述
x, y, x_inc, y_inc, r, color, ch = 3, 3, 1, 1, 3, 31, '@'
#   画布载体
canvas = None

"""
    画布创建
"""
def createCanvas(r, c):
    canvas = list(range(r))
    for x in canvas:
        canvas[x] = list(range(c))

    return canvas

"""
    画布初始化
"""
def initCanvas(canvas, row, col):
    for r in range(row):
        for c in range(col):
            if r == 0 or c == 0 or r == row - 1 or c == col - 1:
                canvas[r][c] = '#'
            else:
                canvas[r][c] = ' '

    return canvas

#   """
#       创建画布并且初始化
#   """
#   def initCanvas(row, col):
    #   canvas = []

    #   for r in range(row):
        #   canvas.append([])
        #   for c in range(col):
            #   if r == 0 or c == 0 or r == row - 1 or c == col - 1:
            #       canvas[r].append('#')
            #   else:
            #       canvas.append(' ')

    #   return canvas

"""
    刷新画布
"""
def showCanvas(canvas, row, col, color, ch):
    print("\033[1;1H", end='', flush=True)
    for r in range(row):
        for c in range(col):
            if canvas[r][c] == ch:
                print("\033[%dm%c\033[m" % (color, ch), end='', flush=True)
            else:
                print(canvas[r][c], end='')
        print()

"""
    在画布上作画
"""
def draw(canvas, row, col, x, y, r, ch):
    for i in range(y, y + r):
        for j in range(x, x + r):
            if i > ROW - 1 or j > COL - 1 or i < 0 or j < 0:
                continue
            canvas[i][j] = ch

"""
    弹球程序的初始化操作
"""
def ball_init(row, col):
    print("\033[2J\033[?25l", end='', flush=True)
    gt.init()
    return createCanvas(row, col)

"""
    弹球程序退出终端还原操作
"""
def ball_exit(row):
    print("\033[%d;1H\033[?25h" % (row + 2), end='', flush=True)
    gt.exit()
    os._exit(0)

"""
    弹球运动控制
"""
def move():
    global x, y, x_inc, y_inc, color

    if x <= 0 or x + r > COL - 1:
        x_inc *= -1
        color = random.randint(30, 37)

    if y <= 0 or y + r > ROW - 1:
        y_inc *= -1
        color = random.randint(30, 37)

    x += x_inc
    y += y_inc

"""
    弹球动画流程
"""
def ball():
    initCanvas(canvas, ROW, COL)
    draw(canvas, ROW, COL, x, y, r, ch)
    move()
    showCanvas(canvas, ROW, COL, color, ch)

    #   下一次动画显示的延时设置
    gt.run(ball, 0.1)

def keyHandle():
    global color, x_inc, y_inc

    while True:
        ch = gt.get()
        if ch == 'q' or ord(ch) == 27:
            break
        elif ch == 'c':
            color = random.randint(30, 37)
        elif ch == 'w':
            y_inc = -1
        elif ch == 's':
            y_inc = 1
        elif ch == 'a':
            x_inc = -1
        elif ch == 'd':
            x_inc = 1

if __name__ == '__main__':
    canvas = ball_init(ROW, COL)
    gt.run(ball)
    keyHandle()
    ball_exit(ROW)
